import { ref, computed , onMounted, watch } from 'vue'
import { defineStore } from 'pinia'
import { getWeather ,getNowWeather} from '@/apis/weather'
// 定义counter空间
export const useCityListStore = defineStore('cityList', () => {

  const cityList = ref([])
  const showCity= ref('')
  const showCityWeather = ref('')
  const setShowCity=(name,adcode)=>{
    let weather=''
    getNowWeather(adcode).then(res => {
      weather = res.data.lives[0]
      console.log(weather)
      showCity.value={adcode,name,weather}
    })
    getWeather(adcode).then(res => {
      showCityWeather.value = res.data.forecasts[0].casts
      console.log(showCityWeather.value)
    })
  }
  const addCityList=()=>{
    cityList.value.push(showCity.value)
  }
  const removeCityList=(adcode)=>{
    cityList.value = cityList.value.filter(item => item.adcode!== adcode)
    console.log(cityList.value)
  }
  const updateCityList=(list)=>{
    list.forEach(item=>{
      getNowWeather(item.adcode).then(res => {
        item.weather = res.data.lives[0]
        console.log(item.weather)
      })
    })
    cityList.value=list
  }
  const getCityWeather=(adcode)=>{
    getWeather(adcode).then(res => {
      showCityWeather.value = res.data.forecasts[0].casts
      console.log(showCityWeather.value)
    })
  }
  // 监听cityList变化，将其存储到localStorage
  watch(cityList, () => {
    //console.log('cityList变化了', cityList.value)
    localStorage.setItem('arr',JSON.stringify(cityList.value))
  }, { deep: true })
  // 页面加载完成后，从localStorage中获取数据
  onMounted(() => {
    if (localStorage.getItem('arr')) {
      //console.log('localStorage中有数据', localStorage.getItem('arr'))
      const arr = JSON.parse(localStorage.getItem('arr'))
      cityList.value = arr
    }
    updateCityList(cityList.value)
  })
   return{cityList,showCity,showCityWeather,getCityWeather,addCityList,setShowCity,removeCityList}
})